<template>
  <el-dialog :title="dataForm.roleId ? '编辑' : '新增'" :visible.sync="visible">
    <el-form ref="dataForm" :rules="dataRule" :model="dataForm" label-position="right" label-width="80px">
      <!-- 角色名称 -->
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="dataForm.roleName" />
      </el-form-item>
      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" />
      </el-form-item>
      <!-- 权限 -->
      <el-form-item size="mini" label="授权">
        <el-tree ref="menuListTree" :data="menuWithPermissions" :props="menuListTreeProps" node-key="menuId"
          show-checkbox />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        {{ '取消' }}
      </el-button>
      <el-button type="primary" @click="dataFormSubmit()">
        {{ '提交' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as api from '@/api/rbac/role'
import * as menuApi from '@/api/rbac/menu'
import { treeDataTranslate } from '@/utils'

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        roleId: 0,
        roleName: null,
        remark: null,
        createUserId: null,
        bizType: null,
        tenantId: null,
        menuIds: [],
        menuPermissionIds: []
      },
      dataRule: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      selectedMenuWithPermissions: [],
      menuWithPermissions: [],
      menuListTreeProps: {
        value: 'menuId',
        label: 'title'
      },
      rules: {
      }
    }
  },
  methods: {
    init(roleId) {
      this.dataForm.roleId = roleId || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.$refs.menuListTree.setCheckedKeys([])
        menuApi.listWithPermissions().then(({ data }) => {
          this.menuWithPermissions = treeDataTranslate(this.handleMenuTree(data), "menuId")
        })
        if (this.dataForm.roleId) {
          api.get(roleId).then(({ data }) => {
            this.dataForm = data
            // 回显选中的选项
            if (data.permissions) {
              let selectedKeys = []
              const newData = treeDataTranslate(this.handleMenuTree(data.permissions), "menuId")
              console.log(newData)
              function getKey(arr) {
                arr.forEach(item => {
                  if (item.children) {
                    getKey(item.children)
                  } else {
                    selectedKeys.push(item.menuId)
                  }
                })
              }
              getKey(newData)
              this.$refs.menuListTree.setCheckedKeys(selectedKeys)
            }
          })
        }
      })
    },
    handleMenuTree(data) {
      data.forEach(menu => {
        // 临时处理，用来区分菜单0和权限1
        menu.type = 0
        menu.title = '菜单: ' + menu.title
        if (menu.permissions && menu.permissions.length) {
          menu.permissions = menu.permissions.filter(permission => permission.menuPermissionId)
          menu.permissions.forEach(permission => {
            permission.type = 1
            permission.menuId = parseInt(permission.menuId + '000' + permission.menuPermissionId)
            permission.title = '资源: ' + permission.name
          })
        } else {
          menu.permissions = null
        }
        menu.children = menu.permissions
      })
      return data
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          const menuIds = []
          const menuPermissionIds = []
          this.$refs.menuListTree.getCheckedNodes(false, true).forEach(node => {
            if (node.type === 0) {
              menuIds.push(node.menuId)
            } else if (node.type === 1) {
              menuPermissionIds.push(node.menuPermissionId)
            }
          })
          this.dataForm.menuIds = menuIds
          this.dataForm.menuPermissionIds = menuPermissionIds
          const request = this.dataForm.roleId ? api.update(this.dataForm) : api.save(this.dataForm)
          request.then(data => {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
                this.$refs['dataForm'].resetFields()
              }
            })
          })
        }
      })
    }
  }
}
</script>
